package gui;

import org.eclipse.swt.widgets.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.*;

import Images.*;
import Drawers.*;
import Interfaces.*;

public class CanvasDlg implements Resizable {
	private Display _display;
	private Shell _shell;
	private MemoryImage _memoryImage;
	private Drawer _lastDrawer;
	public boolean _firstTimeShown;

	public Point CanResize(Point requestedSize)
	{
		if (_memoryImage == null)
			return new Point(0,0);
		
		return _memoryImage.CanResize(requestedSize);
	}
	
	public Point OriginalSize()
	{
		return _memoryImage.OriginalSize();
	}
	
	public boolean Opened()
	{
		if (_firstTimeShown == false)
			return false;
		else	
			return !_shell.isDisposed();
	}
	
	public void Show()
	{
		_firstTimeShown = true;
	
		if (_shell.isDisposed())
			Init();
		
		_shell.open();
	}
	
	public Rectangle GetBounds()
	{
		return _shell.getClientArea();
	}
	
	public CanvasDlg(Display display, MemoryImage image)
	{
		_firstTimeShown = false;
		_display = display;
		_memoryImage = image;
		Init();
	}
	
	private void Init()
	{
		_shell = new Shell(_display);
		_shell.setSize(100, 100);
		
		_shell.addPaintListener(
		
			new PaintListener() 
			{
				public void paintControl(PaintEvent event) 
				{
					Resize(new Point(event.width, event.height));
				}
			});
		
		_memoryImage.setDrawer(new BlittedDrawer(new GC(_shell)));
	}
	
	
	public void Resize(Point p)
	{
		if (_lastDrawer != null)
			_lastDrawer.Stop();
		
		Point drawSize = _memoryImage.CanResize(p);
		Rectangle bounds = _shell.getBounds();
		Rectangle clientArea = _shell.getClientArea();
		
		
		if ((clientArea.width != drawSize.x) || (clientArea.height != drawSize.y))
			_shell.setSize(new Point(drawSize.x + bounds.width - clientArea.width, drawSize.y + bounds.height - clientArea.height));
	
		_memoryImage.Resize(drawSize);
	}
	
	public void ResizeOriginal(Point p)
	{
		_memoryImage.ResizeOriginal(p);
	}
	
}
